package blackstar.agent.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.jetty.security.Constraint;
import org.mortbay.jetty.security.ConstraintMapping;
import org.mortbay.jetty.security.SecurityHandler;

import blackstar.agent.AgentConfig;
import blackstar.agent.security.UserManager;
import blackstar.agent.service.ServiceFactory;

/**
 * @author RayWoo (ayufox@gmail.com)
 *
 */
public class JettySecurityUtil
{
	private final static Log LOGGER = LogFactory
			.getLog(JettySecurityUtil.class);

	public static SecurityHandler createSecurityHandler(String context)
	{
		UserManager authenticator = ServiceFactory.getUserManager();
		if (authenticator == null)
		{
			LOGGER.info("No Authenticator Found");

			return null;
		}

		String securityPatterns = AgentConfig
				.getProperty("security.web." + context + ".patterns");
		if (securityPatterns == null || securityPatterns.trim().length() == 0)
		{
			LOGGER.info("No SecurityPatterns Config Found for [" + context + "]");

			return null;
		}
		
		LOGGER.info("create secuirty context[" +securityPatterns + "] for context[/" + context + "]");

		String[] patterns = securityPatterns.split(",");
		ConstraintMapping[] cms = new ConstraintMapping[patterns.length];

		for (int i = 0; i < cms.length; i++)
		{
			cms[i] = createConstraintMapping(patterns[i]);
		}

		SecurityHandler sh = new SecurityHandler();
		sh.setUserRealm(new AgentUserRealm(authenticator));
		sh.setConstraintMappings(cms);

		return sh;
	}

	private static ConstraintMapping createConstraintMapping(String pattern)
	{
		String[] array = pattern.split(" ");
		if (array.length == 1)
		{
			Constraint constraint = new Constraint();
			constraint.setName(Constraint.__BASIC_AUTH);
			;
			constraint.setRoles(new String[]
			{ "user" });
			constraint.setAuthenticate(true);

			ConstraintMapping cm = new ConstraintMapping();
			cm.setConstraint(constraint);
			cm.setPathSpec(array[0].trim());

			return cm;
		} else if (array.length == 2)
		{
			Constraint constraint = new Constraint();
			constraint.setName(Constraint.__BASIC_AUTH);
			;
			constraint.setRoles(new String[]
			{ array[1].trim() });
			constraint.setAuthenticate(true);

			ConstraintMapping cm = new ConstraintMapping();
			cm.setConstraint(constraint);
			cm.setPathSpec(array[0].trim());

			return cm;
		} else
		{
			throw new IllegalArgumentException("Error Security Pattern["
					+ pattern + "]");
		}
	}
}
